package drive.Service.ServiceFormat;

import com.google.gson.Gson;
import drive.Mapper.ArticleMapper;
import drive.Mapper.CommentMapper;
import drive.Model.Article;
import drive.Service.ServiceInterface.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ArticleServiceA implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private CommentMapper commentMapper;
    private Gson gson = new Gson();

    @Override
    public String findAll() {
        List<Article> list = articleMapper.findAll();
        return gson.toJson(list);
    }

    @Override
    public String findById(int articleId) {
        Article article = articleMapper.findById(articleId);
        return gson.toJson(article);
    }

    @Override
    public String add(Article article) {
        article.setCreationTime(new Date());
        articleMapper.add(article);
        return "发布文章成功";
    }

    @Override
    @Transactional
    public String update(Article article) {
        int result = articleMapper.update(article);
        Article updateArticle = articleMapper.findById(article.getArticleID());
        return gson.toJson(updateArticle);
    }

    @Override
    public String delete(int articleId) {
        int result = articleMapper.delete(articleId);
        commentMapper.delete_article_comment(articleId);
        return "删除文章成功";
    }
}
